document.write("<script src='js/httpUtil.js'></script>");
document.write("<script src='js/common.js'></script>");
document.write("<script src='js/pagination.js'></script>");

var pageSize = 6;
var checkedMenuList = new Array();
var currentPage = 1;

$(document).ready(function () {
    roleList(1);
});

$("#keywordBtn").click(function () {
    roleList(1);
});

function roleList(currentPage) {
    this.currentPage = currentPage;
    var keyword = $("#keyWord").val();
    var jsonObj = {"currentPage": currentPage, "pageSize": pageSize, "keyword": keyword};
    var result = httpPost(baseUrl + "/role/roleList", jsonObj);
    if (result.flag == 1) {
        pagination(result.result.total, pageSize, currentPage, callback)

        var roleList = $('#roleList');
        roleList.empty();
        for (var i = 0; i < result.result.list.length; i++) {
            var role = result.result.list[i];
            var editBtn = "<button class=\"btn btn-sm btn-primary m-b-5 m-t-5\" onclick='editRolePanel(" + role.roleId + ")'>编辑</button>"
            var enabledBtn = editBtn + " <button class=\"btn btn-sm btn-danger m-b-5 m-t-5\"" +
                "onclick='changeStatus(" + role.roleId + ",0," + currentPage + ")'>禁用</button>";
            if (role.enabled != 1) {
                enabledBtn = editBtn + " <button class=\"btn btn-sm btn-info m-b-5 m-t-5\"" +
                    "onclick='changeStatus(" + role.roleId + ",1)'>启用</button>";
            }
            enabledBtn = enabledBtn +
                " <button class=\"btn btn-sm btn-outline-danger m-b-5 m-t-5\"" +
                " onclick='deleteRolePanel(" +  role.roleId +")'>删除</button>"

            roleList.append("<tr class='text-center'>" +
                "<td>" + role.roleName + "</td>" +
                "<td>" + role.roleDesc + "</td>" +
                "<td>" + role.username + "</td>" +
                "<td>" + role.opTime + "</td>" +
                "<td>" + enabledBtn + "</td>" +
                "</tr>")
        }
    } else {
        toastr.error("系统错误", result.msg);
    }
}

function callback(targetPage, currentPage) {
    if (targetPage == 'prev') {
        roleList(currentPage - 1);
    } else if (targetPage == 'next') {
        roleList(currentPage + 1);
    }
}

function changeStatus(roleId, enabled) {
    var jsonObj = {
        "roleId":roleId
    };
    var result = httpPost(baseUrl + "/role/roleDetail", jsonObj);
    if(result.flag==1){
        console.log(recursionAllData(result.result.menus).join(", "))
        var jsonObj = {
            "roleId": roleId,
            "roleName": result.result.roleName,
            "roleDesc": result.result.roleDesc,
            "resourceId": recursionAllData(result.result.menus),
            "enabled": enabled
        }
        var result = httpPost(baseUrl + "/role/editRole", jsonObj);
        if (result.flag == 1) {
            roleList(currentPage);
        } else {
            toastr.error("系统错误", result.msg);
        }
    }
}

function recursionAllData(data) {
    var list = new Array();
    for (var i = 0; i < data.length; i++) {
        if(data[i].enabled == 1){
            list.push(data[i].resourceId)
        }
        if (data[i].children != null) {
            list = list.concat(recursionAllData(data[i].children))
        }
    }
    return list;
}
function recursionTreeData(treeData, isSelected) {
    var treeList = new Array();
    for (var i = 0; i < treeData.length; i++) {
        var enabled = treeData[i].enabled == 1 ? true : false
        var selected = isSelected ? enabled : false
        var result = {title: treeData[i].resourceDesc, key: treeData[i].resourceId, expand: true, select: selected}
        if (treeData[i].children != null) {
            result.children = recursionTreeData(treeData[i].children, isSelected)
        }
        treeList.push(result)
    }
    return treeList;
}

$("#addRolePanelBtn").click(function () {
    $("#addRoleModal").modal('show')
    var jsonObj = {};
    var result = httpPost(baseUrl + "/menu/menuList", jsonObj);
    if (result.flag == 1) {
        var treeList = recursionTreeData(result.result, false)
    } else {
        toastr.error("系统错误", result.msg);
    }

    $("#tree2").dynatree({
        checkbox: true,
        selectMode: 2,
        children: treeList,
        onRender: function (node, nodeSpan) {
            var selKeys = $.map(node.tree.getSelectedNodes(), function (node) {
                return node.data.key;
            });
            checkedMenuList = selKeys
        },
        onSelect: function (select, node) {
            // Get a list of all selected nodes, and convert to a key array:
            var selKeys = $.map(node.tree.getSelectedNodes(), function (node) {
                return node.data.key;
            });
            checkedMenuList = selKeys
        },
        onClick: function (node, event) {
            if (node.getEventTargetType(event) == "title")
                node.toggleSelect();
        },
        onKeydown: function (node, event) {
            if (event.which == 32) {
                node.toggleSelect();
                return false;
            }
        },
        cookieId: "dynatree-Cb3",
        idPrefix: "dynatree-Cb3-"
    });
})

$("#addRoleBtn").click(function () {
    var roleName = $("#roleName").val()
    var roleDesc = $("#roleDesc").val()
    yorickAssert(roleName != "" && roleDesc != "", "请输入完整参数", "参数错误")
    var jsonObj = {
        "roleName": roleName,
        "roleDesc": roleDesc,
        "resourceId": checkedMenuList
    }
    var result = httpPost(baseUrl + "/role/addRole", jsonObj);
    if (result.flag == 1) {
        toastr.success("创建角色成功", "成功");
        $('#addRoleModal').modal('hide');
        $("#tree2").dynatree("destroy");
        roleList(1);
    } else {
        toastr.error("系统错误", result.msg);
    }
})

function editRolePanel(roleId) {
    var jsonObj = {
        "roleId": roleId
    };
    var result = httpPost(baseUrl + "/role/roleDetail", jsonObj);
    if (result.flag == 1) {
        $("#roleId").val(roleId);
        $("#editRoleName").val(result.result.roleName)
        $("#editRoleDesc").val(result.result.roleDesc)
        enabledRadio("enabled", result.result.enabled)
        var treeList = recursionTreeData(result.result.menus, true)
        $("#editTree2").dynatree({
            checkbox: true,
            selectMode: 2,
            children: treeList,
            onRender: function (node, nodeSpan) {
                var selKeys = $.map(node.tree.getSelectedNodes(), function (node) {
                    return node.data.key;
                });
                checkedMenuList = selKeys
            },
            onSelect: function (select, node) {
                // Get a list of all selected nodes, and convert to a key array:
                var selKeys = $.map(node.tree.getSelectedNodes(), function (node) {
                    return node.data.key;
                });
                checkedMenuList = selKeys
            },
            onClick: function (node, event) {
                if (node.getEventTargetType(event) == "title")
                    node.toggleSelect();
            },
            onKeydown: function (node, event) {
                if (event.which == 32) {
                    node.toggleSelect();
                    return false;
                }
            },
            cookieId: "dynatree-Cb3",
            idPrefix: "dynatree-Cb3-"
        });

        $("#editRoleModal").modal('show')
    } else {
        toastr.error("系统错误", result.msg);
    }
}

$("#editRoleBtn").click(function () {
    var roleId = $("#roleId").val();
    var roleName = $("#editRoleName").val()
    var roleDesc = $("#editRoleDesc").val()
    var enabled = $('[name=enabled]:checked').val();
    console.log(checkedMenuList.join(", "))
    var jsonObj = {
        "roleId": roleId,
        "roleName": roleName,
        "roleDesc": roleDesc,
        "resourceId": checkedMenuList,
        "enabled": enabled
    }
    var result = httpPost(baseUrl + "/role/editRole", jsonObj);
    if (result.flag == 1) {
        toastr.success("修改角色成功", "成功");
        $('#editRoleModal').modal('hide');
        roleList(currentPage);
    } else {
        toastr.error("系统错误", result.msg);
    }

})

function deleteRolePanel(roleId, currentPage){
    $("#deleteRoleId").val(roleId)
    $("#currentPage").val(currentPage)
    $("#deleteRoleModal").modal('show')
}

$("#deleteRoleBtn").click(function () {
    var roleId = $("#deleteRoleId").val()
    var currentPage = $("#currentPage").val()
    var jsonObj = { "roleId": roleId }
    var result = httpPost(baseUrl + "/role/deleteRole", jsonObj);
    if (result.flag == 1) {
        toastr.success("删除角色成功", "成功");
        $('#deleteRoleModal').modal('hide');
        roleList(currentPage);
    } else {
        toastr.error("系统错误", result.msg);
    }
})

$('#addRoleModal').on('hidden.bs.modal', function () {
    $("#tree2").dynatree('destroy');
})
$('#editRoleModal').on('hidden.bs.modal', function () {
    $("#editTree2").dynatree('destroy');
})